<template>
  <view class="bg-gray-50 w-[750rpx] pb-[150rpx] box-border bgs">
    <!-- 顶部导航 -->
    <PageHeader title="发布任务" :showBack="true" />


    <!-- 悬赏表单 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <view class="text-[34rpx] font-bold text-gray-800 mb-[30rpx] flex items-center">
        <!-- <IconFont name="edit" class="text-blue-500 mr-[15rpx]" /> -->
        <text>悬赏任务信息</text>
      </view>

      <nut-form ref="formRef" :model="formData">
        <!-- 任务标题 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务标题</text>
          <input v-model="formData.title" type="text" class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border" placeholder="请输入任务标题（50字以内）" />
        </view>

        <!-- 任务分类 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务分类</text>
          <view class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border" @click="showCategoryPicker = true">
            {{ categoryText || "请选择任务分类" }}
          </view>
          <nut-popup v-model:visible="showCategoryPicker" position="bottom" round>
            <nut-picker v-model="categoryValue" :columns="categoryOptions" title="请选择任务分类" @confirm="onCategoryConfirm" @cancel="showCategoryPicker = false" />
          </nut-popup>
        </view>

        <!-- 任务标签 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务标签</text>
          
          <!-- 标签复选框列表 -->
          <view class="flex flex-wrap gap-[16rpx]">
            <view 
              v-for="tag in industryTags" 
              :key="tag.id" 
              class="flex items-center bg-gray-50 border-2 border-gray-200 rounded-[15rpx] px-[20rpx] py-[12rpx] transition-all cursor-pointer"
              :class="selectedTags.includes(tag.id) ? 'bg-blue-50 border-blue-500 text-blue-600' : 'hover:border-gray-300'"
              @click="toggleTag(tag.id)"
            >
              <nut-checkbox 
                :model-value="selectedTags.includes(tag.id)" 
                @click.stop
                @update:model-value="(val) => toggleTag(tag.id)"
                class="mr-[8rpx] pointer-events-auto"
              />
              <text class="text-[26rpx] flex-1" @click="toggleTag(tag.id)">{{ tag.name }}</text>
            </view>
          </view>
          
          <!-- 显示已选标签 -->
          <view v-if="selectedTags.length > 0" class="mt-[20rpx]">
            <text class="text-[24rpx] text-gray-600 mb-[12rpx] block">已选择标签：</text>
            <view class="flex flex-wrap gap-[12rpx]">
              <view 
                v-for="tagId in selectedTags" 
                :key="tagId" 
                class="flex items-center bg-blue-50 text-blue-600 px-[16rpx] py-[8rpx] rounded-[20rpx] text-[24rpx] border border-blue-100"
              >
                <text>{{ getTagName(tagId) }}</text>
                <IconFont name="close" size="8" class="ml-[8rpx] text-blue-400 cursor-pointer" @click="removeTag(tagId)" />
              </view>
            </view>
          </view>
        </view>

        <!-- 任务描述 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">任务描述</text>
          <nut-textarea
            v-model="formData.description"
            style="height: 100%"
            class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 min-h-[120rpx] max-h-[400rpx] box-border resize-none"
            placeholder="请详细描述任务要求、完成标准、注意事项等"
          />
        </view>

        <!-- 适合人群 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">适合人群</text>
          <view class="flex flex-wrap gap-2">
            <view 
              v-for="item in suitablePersons" 
              :key="item.id"
              class="px-3 py-1 rounded-full border transition-all duration-200 cursor-pointer"
              :class="selectedGroupId === item.id ? 'bg-blue-600 border-blue-600 text-white' : 'bg-gray-100 border-gray-300 text-gray-600'"
              @click="selectGroup(item.id)"
            >
              <text class="text-[22rpx]">{{ item.name }}</text>
            </view>
          </view>
        </view>

        <!-- 截止日期 -->
        <view class="mb-[40rpx]">
          <text class="text-[30rpx] font-bold mb-[20rpx] block text-gray-800">截止日期</text>
          <view class="w-full p-[25rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-gray-50 box-border" @click="showDatePicker = true">
            {{ formData.deadline ? formData.deadline : "请选择任务截止日期" }}
          </view>
          <nut-popup v-model:visible="showDatePicker" position="bottom" round>
            <nut-date-picker v-model="dateValue" title="请选择任务截止日期" type="date" :min-date="minDate" @confirm="onDateConfirm" @cancel="showDatePicker = false" />
          </nut-popup>
        </view>
        
      </nut-form>
    </view>

    <!-- 阶段悬赏设置 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <view class="flex justify-between items-center mb-[30rpx]">
        <text class="text-[32rpx] font-bold text-gray-800">阶段任务设置</text>

      </view>

      <view v-for="(stage, index) in stages" :key="index" class="bg-gray-50 rounded-[20rpx] p-[30rpx] mb-[30rpx] relative">
        <!-- 删除按钮 -->
        <view class="absolute top-[20rpx] right-[20rpx] z-10">
          <IconFont v-if="stages.length > 1" name="close" color="#000" size="16" @click="removeStage(index)" />
        </view>

        <view class="flex justify-between items-center mb-[20rpx]">
          <text class="text-[30rpx] font-bold text-gray-800">第{{ index + 1 }}阶段</text>
        </view>

        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-600 mr-[20rpx] w-[150rpx]">阶段金额</text>
          <input
            v-model="stage.price"
            type="digit"
            class="flex-1 p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border"
            placeholder="0"
            min="0.01"
            @input="handlePriceInput"
          />
        </view>

        <!-- 新增的阶段周期部分 -->
        <view class="flex items-center mb-[20rpx]">
          <text class="text-[28rpx] text-gray-600 mr-[20rpx] w-[150rpx]">阶段周期</text>
          <input v-model="stage.cycle" type="number" class="flex-1 p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border" placeholder="0" min="0" />
          <text class="text-[28rpx] text-gray-600 ml-[20rpx] w-[80rpx] text-center">天</text>
        </view>

        <view class="mt-[20rpx]">
          <text class="text-[28rpx] font-medium mb-[15rpx] block">阶段描述</text>
          <input v-model="stage.describe" type="text" class="w-full p-[20rpx] border-2 border-gray-200 rounded-[15rpx] text-[28rpx] bg-white box-border" placeholder="请描述本阶段任务要求" />
        </view>

        <!-- 添加阶段按钮 -->
        <view class="text-center mt-[20rpx] relative">
          <view
            class="bg-white flex items-center justify-center bg-gray-100 active:bg-gray-200 border-1 border-solid border-gray-500 px-[20rpx] py-2 relative z-2 text-gray-500 text-[26rpx] cursor-pointer"
            @click="addStageAfter(index)"
          >
            <IconFont name="plus" class="text-[32rpx]" />添加新阶段
          </view>
        </view>
      </view>
    </view>

    <!-- 金额总计 -->
    <view class="bg-gradient-to-r from-blue-600 to-blue-800 text-white rounded-[25rpx] p-[30rpx] m-[30rpx] flex justify-between items-center box-border">
      <text class="text-[32rpx] font-bold">任务总金额</text>
      <text class="text-[48rpx] font-bold">¥ {{ taskTotal }}</text>
    </view>

    <!-- 服务方选择 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg mb-[30rpx] box-border">
      <view class="text-[32rpx] font-bold mb-[30rpx] flex items-center">
        <!-- <IconFont name="users" class="text-[#2196F3] mr-[15rpx]" /> -->
        <text>服务方选择</text>
      </view>
      <!-- 单选框组 -->
      <nut-radio-group v-model="providerType" direction="horizontal" class="gap-x-[40rpx] mb-[30rpx] flex items-center">
        <nut-radio :label="'all'" class="text-[28rpx] !text-[#2196F3] flex items-center">不限</nut-radio>
        <nut-radio :label="'person'" class="text-[28rpx] !text-[#2196F3] flex items-center">个人从业者</nut-radio>
        <nut-radio :label="'company'" class="text-[28rpx] !text-[#2196F3] flex items-center">服务商</nut-radio>
      </nut-radio-group>

      <!-- 服务商列表 -->
      <view v-if="providerType === 'all' || providerType === 'company'">
        <view class="flex items-center justify-between my-[20rpx]">
          <text class="text-[28rpx] font-medium">可选服务商</text>
          <nut-button 
            type="default" 
            size="small"
            class="!bg-[#165DFF] !text-white !border-[#165DFF] px-[20rpx] py-[8rpx] rounded-[20rpx] text-[24rpx]"
            @click="showCompanySelector = true"
          >
            更多
          </nut-button>
        </view>
        <view class="grid grid-cols-2 gap-[20rpx]">
          <view v-for="company in companyList" :key="company.id" class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]">
            <nut-checkbox :model-value="selectedCompanies.includes(Number(company.id))" @update:model-value="(val) => handleCompanyCheck(val, Number(company.id))" class="mr-[4rpx] !text-[#2196F3]" />
            <view class="flex-1 min-w-0" @tap="viewUser(Number(company.id))">
              <text class="text-[28rpx] font-bold text-gray-800 truncate block">{{ company.name }}</text>
              <text class="block text-[24rpx] text-gray-500 truncate">{{ company.brief_introduction || '暂无简介' }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 个人从业者列表 -->
      <view v-if="providerType === 'all' || providerType === 'person'">
        <view class="flex items-center justify-between my-[20rpx]">
          <text class="text-[28rpx] font-medium">可选个人从业者</text>
          <nut-button 
            type="default" 
            size="small"
            class="!bg-[#165DFF] !text-white !border-[#165DFF] px-[20rpx] py-[8rpx] rounded-[20rpx] text-[24rpx]"
            @click="showPersonSelector = true"
          >
            更多
          </nut-button>
        </view>
        <view class="grid grid-cols-2 gap-[20rpx] mb-[20rpx]">
          <view v-for="person in personList" :key="person.id" class="flex items-center bg-gray-50 rounded-[15rpx] p-[20rpx] border-2 transition-all border-transparent hover:border-[#2196F3]">
            <nut-checkbox :model-value="selectedPersons.includes(Number(person.id))" @update:model-value="(val) => handlePersonCheck(val, Number(person.id))" class="mr-[15rpx] !text-[#2196F3]" />
            <!-- <IconFont name="user" class="text-[36rpx] text-[#2196F3] mr-[10rpx]" /> -->
            <view class="flex-1 min-w-0" @tap="viewUser(Number(person.id))">
              <text class="text-[28rpx] font-bold text-gray-800 truncate block">{{ person.name }}</text>
              <text class="block text-[24rpx] text-gray-500 truncate">{{ person.brief_introduction || '暂无简介' }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 区域选择 -->
    <RegionSelector v-model="regionLevel" @change="handleRegionChange" />

    <!-- 市区选择 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <view class="text-[32rpx] font-bold text-gray-800 mb-[30rpx] flex items-center">
        <IconFont name="location" class="text-blue-500 mr-[15rpx]" />
        <text>服务区域</text>
      </view>
      
      <view class="mb-[20rpx]">
        <text class="text-[28rpx] font-medium text-gray-700 block mb-[15rpx]">选择服务区域</text>
        <view class="text-[24rpx] text-gray-500 mb-[20rpx]">
          <!-- 根据区域选择级别显示不同的说明文字 -->
          <text v-if="regionLevel === 'city'">
            选择任务执行的具体省市，这将影响任务的服务范围和信息费用
          </text>
          <text v-else-if="regionLevel === 'province'">
            选择任务执行的省份，这将影响任务的服务范围和信息费用
          </text>
          <text v-else-if="regionLevel === 'nation'">
            全国范围，无需选择具体区域
          </text>
        </view>
        
        <!-- 市区选择器 -->
        <view :class="{ 'opacity-50 pointer-events-none': isCityPickerDisabled }">
          <CityPicker
            :mode="cityPickerMode"
            :placeholder="cityPickerPlaceholder"
            :title="cityPickerTitle"
            :disabled="isCityPickerDisabled"
            @confirm="handleRegionConfirm"
            @cancel="handleRegionCancel"
          />
        </view>
        
        <!-- 全国范围时的特殊显示 -->
        <view v-if="regionLevel === 'nation'" class="mt-[20rpx] p-[20rpx] bg-green-50 rounded-[15rpx] border border-green-200">
          <view class="flex items-center">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="qiandao" class="text-green-600 mr-[10rpx]" size="15" />
            <text class="text-[26rpx] text-green-800 font-medium">服务范围：</text>
          </view>
          <text class="text-[28rpx] text-green-900 mt-[8rpx] block">
            全国范围
          </text>
        </view>
        
        <!-- 显示已选择的区域 -->
        <view v-else-if="region" class="mt-[20rpx] p-[20rpx] bg-blue-50 rounded-[15rpx] border border-blue-200">
          <view class="flex items-center">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="qiandao" class="text-blue-600 mr-[10rpx]" size="15" />
            <text class="text-[26rpx] text-blue-800 font-medium">已选择区域：</text>
          </view>
          <text class="text-[28rpx] text-blue-900 mt-[8rpx] block">
            {{ regionDisplayText }}
          </text>
        </view>
      </view>
    </view>

    <!-- 支付按钮 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg text-center box-border">
      <nut-button
        type="primary"
        size="large"
        class="w-full text-[36rpx] font-bold bg-gradient-to-r from-orange-400 to-red-500 h-[96rpx]"
        @click="handlePayment"
        :disabled="isSubmitting"
        :loading="isSubmitting"
      >
        <!-- <IconFont name="lock" class="mr-[15rpx]" /> -->
        {{ isSubmitting ? "发布中..." : "支付任务金额并发布" }}
      </nut-button>
      <text class="text-[26rpx] text-gray-600 mt-[30rpx] block"> 支付后金额将托管在平台，任务完成后支付给执行方 </text>
    </view>

    <!-- 地图选择器 -->
    <MapPicker v-model="showMapPicker" :default-location="defaultMapLocation" @confirm="handleLocationConfirm" />

    <!-- 流程说明 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg box-border">
      <text class="text-[32rpx] font-bold text-gray-800 mb-[30rpx] text-center block">任务流程说明</text>

      <view class="flex flex-col gap-[30rpx]">
        <view v-for="(step, index) in processSteps" :key="index" class="flex items-start">
          <view class="w-[50rpx] h-[50rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[30rpx] font-bold mr-[20rpx] flex-shrink-0">
            {{ index + 1 }}
          </view>
          <view class="flex-1">
            <text class="text-[30rpx] font-bold text-gray-800 mb-[10rpx] block">{{ step.title }}</text>
            <text class="text-[26rpx] text-gray-600 leading-[1.5]">{{ step.desc }}</text>
          </view>
        </view>
      </view>

      <view class="bg-yellow-50 border-l-5 border-yellow-400 p-[20rpx] rounded-[10rpx] mt-[20rpx] text-[26rpx] text-gray-600">
        <IconFont name="issue" class="text-yellow-400 mr-[10rpx]" />
        如出现纠纷：任何一方可点击"我有异议"，平台将冻结该笔交易金额，双方协商一致后解锁交易并按流程核销。
      </view>
    </view>

    <!-- 服务商选择弹窗 -->
    <CompanySelectorModal 
      v-model="showCompanySelector" 
      :selected-items="selectedCompanies"
      @confirm="handleCompanySelectorConfirm"
    />

    <!-- 个人从业者选择弹窗 -->
    <PersonSelectorModal 
      v-model="showPersonSelector" 
      :selected-items="selectedPersons"
      @confirm="handlePersonSelectorConfirm"
    />

    <!-- 支付方式选择弹窗 -->
    <PaymentMethodModal 
      v-model="showPaymentModal" 
      :amount="parseFloat(totalAmount)"
      @confirm="handlePaymentConfirm"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// import { Radio as nutRadio, RadioGroup as nutRadioGroup, Checkbox as nutCheckbox } from '@nutui/nutui-taro'
import PageHeader from "@/components/PageHeader.vue";
import MapPicker from "@/components/MapPicker.vue";
import RegionSelector from "@/components/RegionSelector.vue";
import CityPicker from "@/components/CityPicker.vue";
import CompanySelectorModal from "@/components/CompanySelectorModal.vue";
import PersonSelectorModal from "@/components/PersonSelectorModal.vue";
import PaymentMethodModal from "@/components/PaymentMethodModal.vue";
import { post } from "@/utils/request";
// import { getTaskType } from "@/utils/comm";
import { useUserStore } from "@/store/user";

// 定义接口
interface CategoryColumn {
  update_time: null | number;
  create_time: number;
  name: string;
  id: number;
  pic: string;
}

interface CategoryItem {
  columns: CategoryColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

export interface taskRequest {
  city?: string;
  // 周期
  cycle?: string;
  // 截止日期
  deadline?: string;
  // 描述
  describe?: string;
  // 行业ID
  industryId?: string;
  // 纬度
  latitude?: string;
  // 经度
  longitude?: string;
  range?: string;
  // 是否上热门 0 不  1 上
  recommend?: number;
  // 主任务状态  0 发布中 1 进行中 2 待确认完成 3 确认没完成 4 确认已完成
  status?: number;
  taskStages?: TaskStageVo[];
  // 类型
  taskType?: number;
  // 标题
  title?: string;
  // 标签
  tags?: string[];
  // 邀请服务方
  userIds?: number[];
  // 服务方类型 1不限制 2个人 3商家
  serviceProvider?: number;
  [property: string]: any;
}

/**
 * 任务阶段
 *
 * TaskStageVo
 */
export interface TaskStageVo {
  // 任务周期(天)
  cycle?: string | number;
  // 描述
  describe?: string;
  id?: number;
  // 价格
  price?: string | number;
  // 任务状态  0所有  1 发布中  2 进行中 3 待确认完成 4 确认没完成 5 确认已完成(待评价) 6 已评价
  status?: number;
  // 任务ID
  taskId?: number;
  [property: string]: any;
}

// 任务分类选项
const categoryOptions = ref<{ text: string; value: string }[]>([]);

const viewUser = (id: number) => {
  Taro.navigateTo({
    url: `/pages/mine/other?id=${id}`,
  });
};

/**
 * 获取一个月后日期
 * @returns {string} 格式化的日期字符串 YYYY-MM-DD
 */
const getNextMonthDate = () => {
  const now = new Date();
  const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate());

  // 处理月末日期的情况（如1月31日 -> 2月28日/29日）
  if (nextMonth.getMonth() !== (now.getMonth() + 1) % 12) {
    // 如果月份不匹配，说明是月末日期，设置为下个月的最后一天
    nextMonth.setDate(0);
  }

  const year = nextMonth.getFullYear();
  const month = String(nextMonth.getMonth() + 1).padStart(2, "0");
  const day = String(nextMonth.getDate()).padStart(2, "0");

  return `${year}-${month}-${day}`;
};

// 流程步骤
const processSteps = ref([
  { title: "发布任务", desc: "填写任务信息并支付任务金额到平台" },
  { title: "执行方申请", desc: "平台从业者在线申请执行任务" },
  { title: "选择执行方", desc: "您可以选择申请者或邀请特定从业者" },
  { title: "开始执行", desc: "双方同意后正式开始执行任务" },
  { title: "阶段结算", desc: "每个阶段完成后单独结算该阶段金额" },
]);

// 选中状态（保留用于后续扩展）
// const selectedType = ref("daily");
// const selectedRecruitType = ref("");

// 行业标签相关
const industryTags = ref<any[]>([]);
const selectedTags = ref<number[]>([]);

// 适合人群相关
const suitablePersons = ref<any[]>([]);
const selectedGroupId = ref<number>(0); // 默认为"不限"

/**
 * 获取行业标签数据
 */
const getIndustryTags = async () => {
  try {
    const res = await post("/dictionary/industry");
    console.log("行业标签数据:", res);
    if (res.code === 0) {
      industryTags.value = res.data.map((item: any) => ({
        id: item.columns.id,
        name: item.columns.name,
        pic: item.columns.pic
      }));
    }
  } catch (error) {
    console.error("获取行业标签失败:", error);
    Taro.showToast({
      title: "获取标签失败",
      icon: "none"
    });
  }
};

/**
 * 获取适合人群列表
 */
const getSuitablePersons = async () => {
  try {
    const res = await post("/dictionary/groupTypes");
    console.log("res==>人群",res.data)
    if (res.code === 0 && res.data) {
      // 根据接口返回的数据结构处理人群列表
      suitablePersons.value = res.data.map((item: any) => item.columns);
      suitablePersons.value.unshift({ id: 0, name: "不限" });
    }
  } catch (error) {
    console.error("获取适合人群列表失败:", error);
    // 设置默认人群列表作为备用
    suitablePersons.value = [
      { id: 0, name: "不限" },
      { id: 1, name: "学生" },
      { id: 2, name: "上班族" },
      { id: 3, name: "自由职业者" },
      { id: 4, name: "退休人员" }
    ];
  }
};

/**
 * 选择适合人群
 * @param groupId 人群ID
 */
const selectGroup = (groupId: number) => {
  selectedGroupId.value = groupId;
  
  // 显示选择提示
  const groupName = groupId === 0 ? '不限' : suitablePersons.value.find(item => item.id === groupId)?.name || '未知';
  Taro.showToast({
    title: `已选择：${groupName}`,
    icon: 'none',
    duration: 1500
  });
};

/**
 * 切换标签选择状态
 * @param tagId 标签ID
 */
const toggleTag = (tagId: number) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tagId);
  }
};

/**
 * 移除标签
 * @param tagId 标签ID
 */
const removeTag = (tagId: number) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  }
};

/**
 * 根据标签ID获取标签名称
 * @param tagId 标签ID
 * @returns 标签名称
 */
const getTagName = (tagId: number) => {
  const tag = industryTags.value.find(item => item.id === tagId);
  return tag ? tag.name : '';
};

const formData = reactive<taskRequest>({});
// const taskStages = ref<TaskStageVo[]>([]);

// 设置默认截止日期
formData.deadline = getNextMonthDate();

// 阶段数据
const stages = ref<TaskStageVo[]>([{ price: "", describe: "", cycle: "" }]);

// 计算总金额
const taskTotal = computed(() => {
  const stagesTotal = stages.value.reduce((total: number, stage: TaskStageVo) => {
    return total + (parseFloat(String(stage.price || 0)) || 0);
  }, 0);
  return stagesTotal.toFixed(2);
});

const totalAmount = computed(() => {
  // 计算所有阶段价格总和
  const stagesTotal = stages.value.reduce((total: number, stage: TaskStageVo) => {
    return total + (parseFloat(String(stage.price || 0)) || 0);
  }, 0);

  // 加上单独的fee，再统一处理小数位
  return (stagesTotal + (parseFloat(fee.value) || 1)).toFixed(2);
});

// 计算总周期
const totalCycle = computed(() => {
  // 遍历所有阶段，累加周期数值
  return stages.value.reduce((total: number, stage: TaskStageVo) => {
    // 将周期字符串转为数字，空值或非数字按0处理
    return total + (parseInt(String(stage.cycle || 0), 10) || 0);
  }, 0);
});

// 在指定阶段后添加新阶段
const addStageAfter = (index: number) => {
  stages.value.splice(index + 1, 0, { price: "", describe: "", cycle: "" });
};

// 删除阶段
const removeStage = (index: number) => {
  if (stages.value.length > 1) {
    stages.value.splice(index, 1);
  } else {
    Taro.showToast({
      title: "至少需要保留一个阶段",
      icon: "none",
    });
  }
};

// 处理价格输入，支持小数
const handlePriceInput = (event: any) => {
  const value = event.target.value;
  let cleanValue = value.replace(/[^\d.]/g, "");

  // 确保只有一个小数点
  const dotIndex = cleanValue.indexOf(".");
  if (dotIndex !== -1) {
    const beforeDot = cleanValue.substring(0, dotIndex);
    const afterDot = cleanValue.substring(dotIndex + 1).replace(/\./g, "");
    cleanValue = beforeDot + "." + afterDot;
  }

  // 限制小数点后两位
  if (dotIndex !== -1 && cleanValue.length > dotIndex + 3) {
    cleanValue = cleanValue.substring(0, dotIndex + 3);
  }

  // 更新价格值
  event.target.value = cleanValue;
};

// 返回（保留用于后续扩展）
// const handleBack = () => {
//   Taro.navigateBack();
// };

/**
 * 服务方类型
 * @type {import('vue').Ref<'all'|'person'|'company'>}
 */
const providerType = ref<"all" | "person" | "company">("all");

/**
 * 个人从业者模拟数据
 * @type {Array<any>}
 */
const personList = ref<any[]>([]);

/**
 * 服务商模拟数据
 * @type {Array<any>}
 */
const companyList = ref<any[]>([]);

/**
 * 选中的个人从业者ID
 * @type {import('vue').Ref<number[]>}
 */
const selectedPersons = ref<number[]>([]);
/**
 * 选中的服务商ID
 * @type {import('vue').Ref<number[]>}
 */
const selectedCompanies = ref<number[]>([]);

/**
 * 区域选择
 * @type {import('vue').Ref<string>}
 */
const regionLevel = ref("city");

// 区域价格
const fee = ref<string>("1"); //默认是区域是市级
const rangeType = ref<string>("1");
const isSubmitting = ref(false); // 添加提交状态

/**
 * 市区选择相关数据
 */
const region = ref<{
  province?: {
    code: string
    name: string
    level: number
    parentCode?: string
  }
  city?: {
    code: string
    name: string
    level: number
    parentCode?: string
  }
} | null>(null)

// 根据区域选择级别确定市区选择器的模式
const cityPickerMode = computed(() => {
  switch (regionLevel.value) {
    case 'city':
      return 'city' // 市级：可以选择省市
    case 'province':
      return 'province' // 省级：只能选择省份
    case 'nation':
      return 'province' // 全国：不可选择，但设置为province模式
    default:
      return 'city'
  }
})

// 根据区域选择级别确定是否禁用市区选择器
const isCityPickerDisabled = computed(() => {
  return regionLevel.value === 'nation' // 全国时禁用
})

// 选中的区域显示文本
const regionDisplayText = computed(() => {
  if (!region.value) {
    if (regionLevel.value === 'nation') {
      return "全国范围"
    }
    return "请选择服务区域"
  }
  
  if (region.value.city) {
    return `${region.value.province?.name} ${region.value.city.name}`
  }
  
  if (region.value.province) {
    return region.value.province.name
  }
  
  return "请选择服务区域"
})

// 市区选择器的占位符文本
const cityPickerPlaceholder = computed(() => {
  switch (regionLevel.value) {
    case 'city':
      return "请选择服务区域（省市）"
    case 'province':
      return "请选择服务区域（省份）"
    case 'nation':
      return "全国范围"
    default:
      return "请选择服务区域"
  }
})

// 市区选择器的标题文本
const cityPickerTitle = computed(() => {
  switch (regionLevel.value) {
    case 'city':
      return "选择服务区域（省市）"
    case 'province':
      return "选择服务区域（省份）"
    case 'nation':
      return "全国范围"
    default:
      return "选择服务区域"
  }
})

/**
 * 处理区域选择变化
 * @param data 区域选择数据
 */
const handleRegionChange = (data: { value: string; fee: number; range: string }) => {
  fee.value = String(data.fee);
  rangeType.value = data.range;
  
  // 当区域选择改变时，清空之前选择的市区信息
  region.value = null;
  
  console.log('区域选择已改变:', data.value, '清空市区选择');
};

/**
 * 处理市区选择确认
 * @param result 选择结果
 */
const handleRegionConfirm = (result: {
  province?: {
    code: string
    name: string
    level: number
    parentCode?: string
  }
  city?: {
    code: string
    name: string
    level: number
    parentCode?: string
  }
}) => {
  region.value = result
  
  console.log('选择的区域:', result)
  
  // 显示选择结果提示
  let message = ''
  if (result.city) {
    message = `已选择：${result.province?.name} ${result.city.name}`
  } else if (result.province) {
    message = `已选择：${result.province.name}`
  }
  
  if (message) {
    Taro.showToast({
      title: message,
      icon: 'success',
      duration: 2000
    })
  }
}

/**
 * 处理市区选择取消
 */
const handleRegionCancel = () => {
  console.log('取消区域选择')
  Taro.showToast({
    title: '已取消选择',
    icon: 'none',
    duration: 1500
  })
}

// 发布任务
const handlePayment = async () => {
  if (isSubmitting.value) return; // 防止重复提交

  console.log("formData==", formData);
  console.log("stages==", stages.value);
  console.log("tags==", selectedTags.value);

  // 设置loading状态
  isSubmitting.value = true;

  try {
    if (!formData.title) {
      Taro.showToast({
        title: "请填写任务标题",
        icon: "none",
      });
      isSubmitting.value = false;
      return;
    }

    if (!formData.taskType) {
      Taro.showToast({
        title: "请选择任务分类",
        icon: "none",
      });
      isSubmitting.value = false;
      return;
    }

    if (!formData.description) {
      //console.log("提交表单", formData)
      Taro.showToast({
        title: "请填写任务描述",
        icon: "none",
      });
      isSubmitting.value = false;
      return;
    }

    if (selectedTags.value.length === 0) {
      Taro.showToast({
        title: "请至少选择一个任务标签",
        icon: "none",
      });
      isSubmitting.value = false;
      return;
    }

    const total = parseFloat(taskTotal.value);
    if (total <= 0) {
      Taro.showToast({
        title: "请设置任务金额",
        icon: "none",
      });
      isSubmitting.value = false;
      return;
    }

    // 验证地址选择
    if (regionLevel.value === 'province' && !region.value?.province) {
      Taro.showToast({
        title: "请选择服务省份",
        icon: "none",
      });
      isSubmitting.value = false;
      return;
    }

    if (regionLevel.value === 'city' && (!region.value?.province || !region.value?.city)) {
      Taro.showToast({
        title: "请选择服务省市",
        icon: "none",
      });
      isSubmitting.value = false;
      return;
    }
    // 转换服务方类型为数字参数
    const getServiceProviderValue = () => {
      switch (providerType.value) {
        case 'all':
          return 1; // 不限制
        case 'person':
          return 2; // 个人
        case 'company':
          return 3; // 商家
        default:
          return 1; // 默认不限制
      }
    };

    // 构建地址参数
    const buildAddressParam = () => {
      switch (regionLevel.value) {
        case 'nation':
          return '全国'
        case 'province':
          // 省级：直接传省份名称
          if (region.value?.province) {
            return region.value.province.name
          }
          return '未选择省份'
        case 'city':
          // 市级：省-市格式
          if (region.value?.province && region.value?.city) {
            return `${region.value.province.name}-${region.value.city.name}`
          } else if (region.value?.province) {
            return region.value.province.name
          }
          return '未选择区域'
        default:
          return '未选择区域'
      }
    };

    // 打印选中的服务方
    console.log("选中的个人从业者:", selectedPersons.value);
    console.log("选中的服务商:", selectedCompanies.value);
    // 打印区域选择和信息费
    console.log("区域选择:", regionLevel.value, "信息费:", fee.value);
    // 打印市区选择信息
    console.log("选择的市区:", region.value);
    // 打印构建的地址参数
    console.log("构建的地址参数:", buildAddressParam());

    const submitData = {
      title: formData.title,
      taskStages: stages.value,
      taskType: formData.taskType,
      deadline: formData.deadline,
      describe: formData.description,
      cycle: totalCycle.value,
      labels: selectedTags.value.map(tagId => getTagName(tagId)).join(","),
      userIds: selectedPersons.value.concat(selectedCompanies.value),
      serviceProvider: getServiceProviderValue(), // 添加服务方参数
      address: buildAddressParam(), // 添加地址参数
      groupTypes: selectedGroupId.value || 0, // 添加适合人群参数
      // stages: stages.value,
      // longitude: formData.longitude || "-165.9479",
      // latitude: formData.latitude || "28.3201",
      recommend: 0,
      city: "南宁市",
      industryId: "4",
      range: rangeType.value,
    };

    console.log("submitData==", submitData);
    Taro.showModal({
      title: "确认发布",
      content: `任务标题：${formData.title}`,
      success: async (res) => {
        if (res.confirm) {
          // API接口
          const res = await post("/task/save", submitData);
          console.log("==>", res);
          if (res.code == 0) {
            // 显示支付方式选择弹窗
            showPaymentModal.value = true;
            // 保存任务ID用于后续支付
            currentTaskId.value = res.data;
          } else {
            Taro.showToast({
              title: "发布失败",
              icon: "none",
            });
          }
        }
      },
    });
  } catch (error) {
    console.error("发布任务失败:", error);
    Taro.showToast({
      title: "发布失败，请重试",
      icon: "none",
    });
  } finally {
    setTimeout(() => {
      isSubmitting.value = false; // 重置loading状态
    }, 2000);
    // isSubmitting.value = false; // 重置loading状态
  }
};

const showCategoryPicker = ref(false);
const categoryValue = ref<string[]>([]);
const categoryText = ref();

// 地图选择器相关
const showMapPicker = ref(false);
const defaultMapLocation = ref({
  latitude: 39.9042,
  longitude: 116.4074,
  address: "北京市",
});

// 服务商选择弹窗相关
const showCompanySelector = ref(false);

// 个人从业者选择弹窗相关
const showPersonSelector = ref(false);

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);

// 用户store
const userStore = useUserStore();

// 当前任务ID（用于支付）
const currentTaskId = ref<number | null>(null);
function onCategoryConfirm(val: any) {
  showCategoryPicker.value = false;
  if (val.selectedValue && val.selectedValue.length > 0) {
    categoryValue.value = [String(val.selectedValue[0])];
    categoryText.value = categoryOptions.value.find((item) => item.value === String(val.selectedValue[0]))?.text;
    formData.taskType = Number(val.selectedValue[0]);
  }
  console.log(formData.taskType);
}

// 任务类别
getCategoryText();
function getCategoryText() {
  post("/dictionary/taskType").then((res) => {
    categoryOptions.value = res.data.map((item: CategoryItem) => ({
      text: item.columns.name,
      value: item.columns.id.toString(),
    }));
  });
}

// 个人从业者列表
const getPersonal = async () => {
  const res = await post("/dictionary/personal", {
    pageNo: 1,
    pageSize: 6,
  });
  console.log("==>", res);
  if (res.code == 0) {
    const ary = res.data.map((item: any) => ({
      ...item.columns,
      // id: item.columns.id,
      // name: item.columns.real_name,
      // desc: item.columns.brief_introduction,
    }));
    personList.value = ary.slice(0, 4);
  }
};
const getMerchant = async () => {
  const res = await post("/dictionary/merchant", {
    pageNo: 1,
    pageSize: 6,
  });
  console.log("==>", res);
  if (res.code == 0) {
    const ary = res.data.map((item: any) => ({
      ...item.columns
      // id: item.columns.id,
      // name: item.columns.real_name,
      // desc: item.columns.brief_introduction,
    }));
    companyList.value = ary.slice(0, 4);
  }
};
getPersonal();
getMerchant();

/**
 * 处理支付方式确认
 * @param method 支付方式
 */
const handlePaymentConfirm = async (method: 'balance' | 'wechat') => {
  if (!currentTaskId.value) {
    Taro.showToast({
      title: "任务ID不存在",
      icon: "none",
    });
    return;
  }

  try {
    // 调用支付接口
    const payRes = await post("/pay/task", {
      amount: totalAmount.value,
      bid: currentTaskId.value,
      vipType: 1,
      deductionBalance: method === 'balance' ? 1 : 0, // 余额支付传1，微信支付传0
    });

    if (payRes.code == 0) {
      if (method === 'wechat') {
        // 微信支付
        doPay(payRes.data);
      } else {
        // 余额支付
        if (payRes.data.code == 2) {
          // 余额支付成功
          Taro.showToast({
            title: "支付成功！",
            icon: "success",
            duration: 2000,
          });
          // 更新用户余额
          const newBalance = (userStore.userInfo.balance || 0) - parseFloat(totalAmount.value);
          userStore.updateBalance(newBalance);
        } else {
          // 余额支付失败
          Taro.showToast({
            title: payRes.data.msg || "支付失败",
            icon: "error",
            duration: 2000,
          });
          return; // 支付失败，不继续执行后续逻辑
        }
      }
      
      Taro.showToast({
        title: `任务发布成功！`,
        icon: "success",
        duration: 2000,
      });
      
      setTimeout(() => {
        Taro.navigateBack();
      }, 2000);
    } else {
      Taro.showToast({
        title: "支付失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("支付失败:", error);
    Taro.showToast({
      title: "支付失败，请重试",
      icon: "none",
    });
  } finally {
    isSubmitting.value = false; // 重置loading状态
    currentTaskId.value = null; // 清空任务ID
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  isSubmitting.value = false; // 重置loading状态
  currentTaskId.value = null; // 清空任务ID
  Taro.showToast({
    title: "已取消支付",
    icon: "none",
  });
};

// 支付发布任务费用（保留原函数用于兼容，已废弃）
// const payTask = async (id: number) => {
//   try {
//     const payRes = await post("/pay/task", {
//       amount: totalAmount.value,
//       bid: id,
//       vipType: 1,
//     });
//     if (payRes.code == 0) {
//       doPay(payRes.data);
//       Taro.showToast({
//         title: `任务发布成功！总金额：¥${totalAmount.value}`,
//         icon: "success",
//         duration: 2000,
//       });
//       setTimeout(() => {
//         Taro.navigateBack();
//       }, 2000);
//     } else {
//       Taro.showToast({
//         title: "支付失败",
//         icon: "none",
//       });
//     }
//   } catch (error) {
//     console.error("支付失败:", error);
//     Taro.showToast({
//       title: "支付失败，请重试",
//       icon: "none",
//     });
//   } finally {
//     isSubmitting.value = false; // 重置loading状态
//   }
// };

// 微信弹窗
const doPay = (param: any) => {
  (window as any).WeixinJSBridge.invoke(
    "getBrandWCPayRequest",
    {
      appId: param.appid, //公众号ID，由商户传入
      timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
      nonceStr: param.nonceStr, //随机串
      package: param.prepayId,
      signType: "RSA", //微信签名方式：
      paySign: param.paySign, //微信签名
    },
    function (param: any) {
      if (param.err_msg == "get_brand_wcpay_request:ok") {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
        Taro.showToast({
          title: "购买成功！",
          icon: "success",
          duration: 2000,
        });
      } else {
        Taro.showToast({ title: "购买失败！", icon: "error", duration: 2000 });
      }
    }
  );
};

const showDatePicker = ref(false);
const dateValue = ref<[number, number, number]>([2024, 1, 1]);

// 最小日期（今天）
const minDate = new Date();

/**
 * 将日期字符串转换为nut-date-picker需要的数组格式
 * @param {string} dateStr - 日期字符串 YYYY-MM-DD
 * @returns {[number, number, number]} [年, 月, 日]
 */
const parseDateToArray = (dateStr: string): [number, number, number] => {
  if (!dateStr) {
    const defaultDate = getNextMonthDate();
    const [year, month, day] = defaultDate.split("-").map(Number);
    return [year, month, day];
  }

  const [year, month, day] = dateStr.split("-").map(Number);
  return [year, month, day];
};

/**
 * 将nut-date-picker的数组格式转换为日期字符串
 * @param {any} val - nut-date-picker的值
 * @returns {string} 格式化的日期字符串 YYYY-MM-DD
 */
const parseArrayToDate = (val: any): string => {
  if (!val) return "";

  if (Array.isArray(val)) {
    const [year, month, day] = val;
    return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
  }

  if (typeof val === "string") {
    if (/^\d{4}-\d{2}-\d{2}$/.test(val)) return val;
    if (/^\d{4}\/\d{2}\/\d{2}$/.test(val)) return val.replace(/\//g, "-");
    return val;
  }

  if (val && typeof val === "object" && Array.isArray(val.selectedValue)) {
    return val.selectedValue.join("-");
  }

  return "";
};

function onDateConfirm(val: any) {
  showDatePicker.value = false;
  // 将nut-date-picker的值转换为日期字符串并存入formData
  formData.deadline = parseArrayToDate(val);
  // 更新dateValue以保持同步
  dateValue.value = val;
}

// 格式化日期字符串（保留用于后续扩展）
// function formatDate(val: any) {
//   if (!val) return "";
//   if (typeof val === "string") {
//     if (/^\d{4}-\d{2}-\d{2}$/.test(val)) return val;
//     if (/^\d{4}\/\d{2}\/\d{2}$/.test(val)) return val.replace(/\//g, "-");
//     return val;
//   }
//   if (val && typeof val === "object" && Array.isArray(val.selectedValue)) {
//     return val.selectedValue.join("-");
//   }
//   return "";
// }

const handlePersonCheck = (val: boolean, id: number) => {
  const idx = selectedPersons.value.indexOf(id);
  if (val && idx === -1) selectedPersons.value.push(id);
  if (!val && idx !== -1) selectedPersons.value.splice(idx, 1);
};
const handleCompanyCheck = (val: boolean, id: number) => {
  const idx = selectedCompanies.value.indexOf(id);
  if (val && idx === -1) selectedCompanies.value.push(id);
  if (!val && idx !== -1) selectedCompanies.value.splice(idx, 1);
};

// 处理服务商选择弹窗确认
const handleCompanySelectorConfirm = (selectedCompanyList: any[]) => {
  console.log('选中的服务商:', selectedCompanyList);
  
  // 将选中的服务商添加到 companyList，如果 id 存在就不添加
  selectedCompanyList.forEach(company => {
    const existingIndex = companyList.value.findIndex(item => item.id === company.id);
    if (existingIndex === -1) {
      // 如果 id 不存在，则添加
      companyList.value.push(company);
    }
  });
  
  // 同时更新选中的服务商ID列表
  selectedCompanies.value = selectedCompanyList.map(company => company.id);
  
  Taro.showToast({
    title: `已选择 ${companyList.value.length} 个服务商`,
    icon: 'success'
  });
};

// 处理个人从业者选择弹窗确认
const handlePersonSelectorConfirm = (selectedPersonList: any[]) => {
  console.log('选中的个人从业者:', selectedPersonList);
  
  // 将选中的个人从业者添加到 personList，如果 id 存在就不添加
  selectedPersonList.forEach(person => {
    const existingIndex = personList.value.findIndex(item => item.id === person.id);
    if (existingIndex === -1) {
      // 如果 id 不存在，则添加
      personList.value.push(person);
    }
  });
  
  // 同时更新选中的个人从业者ID列表
  selectedPersons.value = selectedPersonList.map(person => person.id);
  
  Taro.showToast({
    title: `已选择 ${personList.value.length} 个个人从业者`,
    icon: 'success'
  });
};

/**
 * 处理位置确认
 */
const handleLocationConfirm = (location: any) => {
  formData.location = location.address;
  // 更新提交数据中的经纬度
  formData.longitude = location.longitude;
  formData.latitude = location.latitude;

  Taro.showToast({
    title: "位置选择成功",
    icon: "success",
  });
};

// 页面加载时设置默认截止日期
onMounted(() => {
  // 如果还没有设置截止日期，则设置为一个月后
  if (!formData.deadline) {
    const nextMonthDate = getNextMonthDate();
    formData.deadline = nextMonthDate;
    dateValue.value = parseDateToArray(formData.deadline);
  } else {
    // 确保 dateValue 与 formData.deadline 同步
    dateValue.value = parseDateToArray(formData.deadline);
  }
  
  // 获取行业标签数据
  getIndustryTags();
  
  // 获取适合人群数据
  getSuitablePersons();
});

defineExpose({ handlePersonCheck, handleCompanyCheck });
</script>

<style lang="scss">
.bgs {
  .nut-cell-group__wrap {
    box-shadow: none !important;
  }
  .nut-checkbox {
    margin-right: 0 !important;
  }
  .nut-radio {
    margin-right: 0 !important;
    margin-bottom: 0 !important;
  }
}

.nut-textarea {
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
}
</style>
